package thoven.achievement.net.jsonutil.action

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.ui.Messages
import thoven.achievement.net.jsonutil.service.JsonCleaner
import thoven.achievement.net.jsonutil.service.JwtService

/**
 * JWT 生成操作
 */
class JwtGenerateAction : AnAction() {
    
    override fun actionPerformed(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR) ?: return
        val project = e.project ?: return
        val document = editor.document
        
        val selectionModel = editor.selectionModel
        val selectedText = selectionModel.selectedText
        
        if (selectedText.isNullOrBlank()) {
            Messages.showWarningDialog(
                project,
                "请选中 JSON 文本作为 JWT Payload",
                "生成 JWT"
            )
            return
        }
        
        // 询问密钥
        val secret = Messages.showInputDialog(
            project,
            "请输入 JWT 密钥 (Secret):",
            "生成 JWT",
            null,
            "your-256-bit-secret",
            null
        ) ?: return
        
        // 询问过期时间
        val expirationStr = Messages.showInputDialog(
            project,
            "请输入过期时间（分钟）:",
            "生成 JWT",
            null,
            "60",
            null
        ) ?: return
        
        val expiration = expirationStr.toIntOrNull() ?: 60
        
        // 清理 JSON
        val cleanResult = JsonCleaner.clean(selectedText)
        if (cleanResult.isFailure) {
            Messages.showErrorDialog(
                project,
                "JSON 格式错误: ${cleanResult.exceptionOrNull()?.message}",
                "生成 JWT 错误"
            )
            return
        }
        
        val cleanedJson = cleanResult.getOrNull() ?: return
        val result = JwtService.generateFromJson(cleanedJson, secret, expiration)
        
        if (result.isSuccess) {
            val token = result.getOrNull() ?: return
            
            WriteCommandAction.runWriteCommandAction(project) {
                document.replaceString(
                    selectionModel.selectionStart,
                    selectionModel.selectionEnd,
                    token
                )
            }
            
            Messages.showInfoMessage(
                project,
                "JWT Token 已生成！\n有效期: $expiration 分钟",
                "生成成功"
            )
        } else {
            Messages.showErrorDialog(
                project,
                "生成失败: ${result.exceptionOrNull()?.message}",
                "生成 JWT 错误"
            )
        }
    }
    
    override fun update(e: AnActionEvent) {
        val editor = e.getData(CommonDataKeys.EDITOR)
        val hasSelection = editor?.selectionModel?.hasSelection() == true
        e.presentation.isEnabledAndVisible = hasSelection
    }
}

